[[...path]].page.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import React, { useEffect } from 'react';
  2. import { type IPagePopulatedToShowRevision, getIdForRef } from '@growi/core';
  3. import type {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  11. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  12. import { ShareLinkPageView } from '~/components/ShareLinkPageView';
  13. import type { SupportedActionType } from '~/interfaces/activity';
  14. import { SupportedAction } from '~/interfaces/activity';
  15. import type { CrowiRequest } from '~/interfaces/crowi-request';
  16. import { RegistrationMode } from '~/interfaces/registration-mode';
  17. import type { RendererConfig } from '~/interfaces/services/renderer';
  18. import type { IShareLinkHasId } from '~/interfaces/share-link';
  19. import type { PageDocument, PageModel } from '~/server/models/page';
  20. import ShareLink from '~/server/models/share-link';
  21. import {
  22. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  23. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid, useIsEnabledMarp,
  24. useIsLocalAccountRegistrationEnabled,
  25. } from '~/stores-universal/context';
  26. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  27. import loggerFactory from '~/utils/logger';
  28. import type { NextPageWithLayout } from '../_app.page';
  29. import type { CommonProps } from '../utils/commons';
  30. import {
  31. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, skipSSR, addActivity,
  32. } from '../utils/commons';
  33. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  34. const logger = loggerFactory('growi:next-page:share');
  35. type Props = CommonProps & {
  36. shareLinkRelatedPage?: IShareLinkRelatedPage,
  37. shareLink?: IShareLinkHasId,
  38. isNotFound: boolean,
  39. isExpired: boolean,
  40. disableLinkSharing: boolean,
  41. isSearchServiceConfigured: boolean,
  42. isSearchServiceReachable: boolean,
  43. isSearchScopeChildrenAsDefault: boolean,
  44. isEnabledMarp: boolean,
  45. isLocalAccountRegistrationEnabled: boolean,
  46. drawioUri: string | null,
  47. rendererConfig: RendererConfig,
  48. skipSSR: boolean,
  49. ssrMaxRevisionBodyLength: number,
  50. };
  51. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  52. superjson.registerCustom<IShareLinkRelatedPage, string>(
  53. {
  54. isApplicable: (v): v is IShareLinkRelatedPage => {
  55. return v != null
  56. && v.toObject != null;
  57. },
  58. serialize: (v) => { return superjson.stringify(v.toObject()) },
  59. deserialize: (v) => { return superjson.parse(v) },
  60. },
  61. 'IShareLinkRelatedPageTransformer',
  62. );
  63. // GrowiContextualSubNavigation for shared page
  64. // get page info from props not to send request 'GET /page' from client
  65. type GrowiContextualSubNavigationForSharedPageProps = {
  66. page?: IPagePopulatedToShowRevision,
  67. isLinkSharingDisabled: boolean,
  68. }
  69. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  70. const { page, isLinkSharingDisabled } = props;
  71. return (
  72. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled} />
  73. );
  74. };
  75. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  76. useCurrentPathname(props.shareLink?.relatedPage.path);
  77. useIsSearchPage(false);
  78. useIsNotFound(props.isNotFound);
  79. useShareLinkId(props.shareLink?._id);
  80. useCurrentPageId(props.shareLink?.relatedPage._id);
  81. useCurrentUser(props.currentUser);
  82. useRendererConfig(props.rendererConfig);
  83. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  84. useIsSearchServiceReachable(props.isSearchServiceReachable);
  85. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  86. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  87. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  88. useIsContainerFluid(props.isContainerFluid);
  89. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  90. useEffect(() => {
  91. if (!props.skipSSR) {
  92. return;
  93. }
  94. if (props.shareLink?.relatedPage._id != null && !props.isNotFound) {
  95. mutateCurrentPage();
  96. }
  97. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  98. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  99. const title = generateCustomTitleForPage(props, pagePath);
  100. return (
  101. <>
  102. <Head>
  103. <title>{title}</title>
  104. </Head>
  105. <div className="dynamic-layout-root justify-content-between">
  106. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  107. <ShareLinkPageView
  108. pagePath={pagePath}
  109. rendererConfig={props.rendererConfig}
  110. page={currentPage ?? props.shareLinkRelatedPage}
  111. shareLink={props.shareLink}
  112. isExpired={props.isExpired}
  113. disableLinkSharing={props.disableLinkSharing}
  114. />
  115. </div>
  116. </>
  117. );
  118. };
  119. SharedPage.getLayout = function getLayout(page) {
  120. return (
  121. <>
  122. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  123. <ShareLinkLayout>{page}</ShareLinkLayout>
  124. </>
  125. );
  126. };
  127. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  128. const req: CrowiRequest = context.req as CrowiRequest;
  129. const { crowi } = req;
  130. const { configManager, searchService } = crowi;
  131. props.disableLinkSharing = configManager.getConfig('security:disableLinkSharing');
  132. props.isSearchServiceConfigured = searchService.isConfigured;
  133. props.isSearchServiceReachable = searchService.isReachable;
  134. props.isSearchScopeChildrenAsDefault = configManager.getConfig('customize:isSearchScopeChildrenAsDefault');
  135. props.drawioUri = configManager.getConfig('app:drawioUri');
  136. props.isLocalAccountRegistrationEnabled = crowi.passportService.isLocalStrategySetup
  137. && configManager.getConfig('security:registrationMode') !== RegistrationMode.CLOSED;
  138. props.rendererConfig = {
  139. isSharedPage: true,
  140. isEnabledLinebreaks: configManager.getConfig('markdown:isEnabledLinebreaks'),
  141. isEnabledLinebreaksInComments: configManager.getConfig('markdown:isEnabledLinebreaksInComments'),
  142. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  143. adminPreferredIndentSize: configManager.getConfig('markdown:adminPreferredIndentSize'),
  144. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  145. drawioUri: configManager.getConfig('app:drawioUri'),
  146. plantumlUri: configManager.getConfig('app:plantumlUri'),
  147. // XSS Options
  148. isEnabledXssPrevention: configManager.getConfig('markdown:rehypeSanitize:isEnabledPrevention'),
  149. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  150. customTagWhitelist: crowi.configManager.getConfig('markdown:rehypeSanitize:tagNames'),
  151. customAttrWhitelist: configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  152. ? JSON.parse(configManager.getConfig('markdown:rehypeSanitize:attributes'))
  153. : undefined,
  154. highlightJsStyleBorder: crowi.configManager.getConfig('customize:highlightJsStyleBorder'),
  155. };
  156. props.ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  157. }
  158. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  159. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  160. props._nextI18Next = nextI18NextConfig._nextI18Next;
  161. }
  162. function getAction(props: Props): SupportedActionType {
  163. let action: SupportedActionType;
  164. if (props.isExpired) {
  165. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  166. }
  167. else if (props.shareLink == null) {
  168. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  169. }
  170. else {
  171. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  172. }
  173. return action;
  174. }
  175. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  176. const req = context.req as CrowiRequest;
  177. const { crowi, params } = req;
  178. const result = await getServerSideCommonProps(context);
  179. if (!('props' in result)) {
  180. throw new Error('invalid getSSP result');
  181. }
  182. const props: Props = result.props as Props;
  183. try {
  184. const shareLink = await ShareLink.findOne({ _id: params.linkId }).populate('relatedPage');
  185. if (shareLink == null) {
  186. props.isNotFound = true;
  187. }
  188. else {
  189. props.isNotFound = false;
  190. props.isExpired = shareLink.isExpired();
  191. props.shareLink = shareLink.toObject();
  192. // retrieve Page
  193. const Page = crowi.model('Page') as PageModel;
  194. const relatedPage = await Page.findOne({ _id: getIdForRef(shareLink.relatedPage) });
  195. // determine whether skip SSR
  196. const ssrMaxRevisionBodyLength = crowi.configManager.getConfig('app:ssrMaxRevisionBodyLength');
  197. if (relatedPage != null) {
  198. props.skipSSR = await skipSSR(relatedPage, ssrMaxRevisionBodyLength);
  199. // populate
  200. props.shareLinkRelatedPage = await relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  201. }
  202. }
  203. }
  204. catch (err) {
  205. logger.error(err);
  206. }
  207. injectServerConfigurations(context, props);
  208. await injectNextI18NextConfigurations(context, props);
  209. await addActivity(context, getAction(props));
  210. return {
  211. props,
  212. };
  213. };
  214. export default SharedPage;